package org.dreamfly.dreamalarm.service;

import java.util.Calendar;

import org.dreamfly.dreamalarm.Constants;
import org.dreamfly.dreamalarm.bean.Alarm;
import org.dreamfly.dreamalarm.inter.HandleComponent;
import org.dreamfly.dreamalarm.receiver.AlarmReceiver;
import org.dreamfly.dreamalarm.task.HandleAsyncTask;
import org.dreamfly.dreamalarm.util.DreamAlarmDateFormat;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class LocalService extends Service implements HandleComponent{

	@Override
	public void onCreate(){
		super.onCreate();
	}
	
	@Override
	public int onStartCommand(Intent intent , int flags , int startId){
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
	}
	
	// -------------------------------------------------------------------------------
	// binder 处理来自activity的调用
	// -------------------------------------------------------------------------------
	
	private LocalBinder binder = new LocalBinder();  
   
	public class LocalBinder extends Binder {    
		public LocalService getService() {          
			return LocalService.this;       
		}
   }    
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return binder;
	}  

	// -------------------------------------------------------------------------------
	// 闹钟设定、取消（所有的设定需要在此activity完成，其他页面传递Alarm）
	// -------------------------------------------------------------------------------
	
	/**
	 * 关闭闹钟：如果不重复则关闭
	 * @param alarm
	 */
	public void endAlarm(Alarm alarm){
		Log.d(Constants.LOGTAG,"end the alarm.");
		if(alarm.getReringInterval()!=0){
			broadcastAlarm(alarm);
		}else{
			alarm.setState(Alarm.TURN_OFF);
			handle(alarm,true);
		}
	}
	
	/**
	 * 广播闹钟信息,当日或下一次响起
	 * 
	 * @param context
	 * @param alarm
	 */
	public void broadcastAlarm(Alarm alarm) {
		Log.d(Constants.LOGTAG,"broadcast next alarm.");
		broadcastAlarm(alarm,DreamAlarmDateFormat.getNextCalendar(alarm,false));
	}
	
	/**
	 * 一键起床时关闭闹钟
	 * @param alarm
	 */
	public void getUpEndAlarm(Alarm alarm){
		Log.d(Constants.LOGTAG,"one key to get up.");
		cancelAlarm(alarm.getId());
		broadcastAlarm(alarm,DreamAlarmDateFormat.getNextCalendar(alarm,true));
	}
	
	/**
	 * 重响
	 * @param alarm
	 */
	public void delayRinging(Alarm alarm){
		Calendar calendar=Calendar.getInstance();
		calendar.setTimeInMillis(calendar.getTimeInMillis()+alarm.getReringIntervalMillis());
		broadcastAlarm(alarm,calendar);
	}
	
	/**
	 * 仅仅完成发布广播的操作
	 * @param alarm
	 * @param calendar
	 */
	private void broadcastAlarm(Alarm alarm,Calendar calendar){
		if(DreamAlarmDateFormat.laterThanNow(calendar)){
			// 建立Intent和PendingIntent来调用闹钟管理器
			Intent intent = new Intent(this, AlarmReceiver.class);
			intent.putExtra(Constants.KEY_BETWEEN_ACTIVITY_ALARM, alarm);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
					alarm.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
			// 获取闹钟管理器
			AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
			// 设置闹钟
			alarmManager.set(AlarmManager.RTC_WAKEUP, 
					calendar.getTimeInMillis(), 
					pendingIntent);
		}
		
	}

	/**
	 * 取消闹钟广播
	 * 
	 * @param alarm
	 */
	public void cancelAlarm(int id) {
		Intent intent = new Intent(this, AlarmReceiver.class);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, intent, 0);
		// 获取闹钟管理器
		AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
		alarmManager.cancel(pendingIntent);
	}

	@Override
	public void handle(Alarm alarm, boolean turnChanged) {
		// TODO Auto-generated method stub
		HandleAsyncTask task = new HandleAsyncTask(this, this, alarm, false, turnChanged);
		task.execute();
	}

	@Override
	public void handleSuccessRefresh(boolean isAdd, Alarm alarm,
			boolean turnChanged) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void handleErrorRefresh() {
		// TODO Auto-generated method stub
		
	}
}
